// src/stores/user.ts
import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

// 用户信息的元数据
export interface UserField {
  key: string;                          // 字段变量名
  label: string;                        // 中文名称
  type: 'text' | 'password' | 'select'; // 输入类型
  required: boolean;                    // 是否必填
  minLength?: number;                   // 最小长度（可选）
  placeholder?: string;                 // 占位符（可选）
}

// 注册用户的字段配置
export const userFields: UserField[] = [
  { key: 'username', label: '用户名', type: 'text', required: true, placeholder: '请输入用户名' },
  { key: 'password', label: '密码', type: 'password', required: true, minLength: 6, placeholder: '请输入密码' },
  { key: 'realName', label: '真实姓名', type: 'text', required: true, placeholder: '请输入真实姓名' },
  { key: 'role', label: '角色', type: 'select', required: true, placeholder: '请选择角色' },
];

export interface User {
  id: number;
  username: string;
  password: string;
  realName: string;
  role: string;
}

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    users: [] as User[],
  }),

  actions: {
    setUser(userData: any) {
      this.user = userData;
    },

    async login(username: string, password: string) {
      try {
        const response = await axios.post('/users/login', { username, password });
        this.setUser(response.data.data);
        return response.data;
      } catch (error) {
        throw error;
      }
    },

    async register(userData: { [key: string]: any }) {
      try {
        const response = await axios.post('/users/register', userData);
        this.setUser(response.data.data);
        return response.data;
      } catch (error) {
        throw error;
      }
    },

    async fetchUserInfo(userId: number) {
      try {
        const response = await axios.get(`/users/${userId}`);
        if (response.data.code === 200) {
          this.setUser(response.data.data);
          return response.data.data;
        } else {
          throw new Error(response.data.message || '获取用户信息失败');
        }
      } catch (error) {
        throw error;
      }
    },

    async fetchUsers() {
      try {
        const response = await axios.get('/users');
        if (response.data.code === 200) {
          this.users = response.data.data;
          console.log('用户列表:', this.users); // 调试日志
          return this.users;
        } else {
          throw new Error(response.data.message || '获取用户列表失败');
        }
      } catch (error) {
        console.error('用户列表加载失败:', error);
        throw new Error('获取用户列表失败');
      }
    },

    logout() {
      this.user = null;
    },
  },
});